package com.right.health.app.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;

import com.magic.basic.activity.BaseConstants;
import com.magic.basic.activity.BaseUtils;
import com.magic.basic.utils.CollectionUtil;
import com.magic.basic.utils.LogUtil;
import com.magic.basic.utils.ToastUtil;
import com.right.health.app.base.delegate.OnProessViewDelegate;

import java.util.List;

/**
 * Base Presenter View
 * <p>
 * Created by Hope on 17/3/1.
 */

public abstract class BasePresenterView<T extends IBasePresenter,K> extends LinearLayout implements IBaseView<K> {

    private T mPresenter;

    protected OnProessViewDelegate mDelegate;

    private List<IBasePresenter> mSelfPresenter;

    private View mContentView;

    protected String mCurrentTag;

    public BasePresenterView(Context context) {
        super(context);

        initConfig();
    }

    public BasePresenterView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

        initConfig();
    }

    public BasePresenterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initConfig();
    }

    public void sendBroadcast(int value) {
        sendBroadcast(value, null);
    }

    public void sendBroadcast(int value, Bundle bundle) {
        BaseUtils.sendBroadcast(getContext(), value, bundle);
    }


    private void initConfig() {
        mContentView = onCreateView();
        if (mContentView == null) {
            throw new NullPointerException("content view is null");
        }
        addView(mContentView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        mPresenter = createPresenter();
        mSelfPresenter = createSelfPresenter();

        if (mPresenter != null) {
            mPresenter.attachView(this);
        }

        if (getSelfPresenter() != null) {
            int size = getSelfPresenter().size();
            for (int i = 0; i < size; i++) {
                getSelfPresenter().get(i).attachView(this);
            }
        }

        registerReceiver();

        findViews();
        initialize();
    }

    private void registerReceiver() {
        try {
            PackageInfo info = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0);
            // 注册拿到加载状态广播接收器

            LocalBroadcastManager.getInstance(getContext()).registerReceiver(
                    broadcastReceiver,
                    new IntentFilter(info.packageName + BaseConstants.BROADCASE_ADDRESS));
        } catch (Exception e) {
            LogUtil.error(getClass(), e.getMessage());
        }
    }

    public String getCurrentTag() {
        return mCurrentTag;
    }

    // 注册广播 ,用于接收耗时任务的处理进度
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (getContext() == null) {  //有可能资源被释放了
                    return;
                }

                PackageInfo info = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0);

                if (intent.getAction().equals(info.packageName + BaseConstants.BROADCASE_ADDRESS)) {
                    Bundle bundle = intent.getExtras();

                    Integer i = bundle.getInt(BaseConstants.BROADCASE_INTENT);
                    onReceiveBroadcast(i, intent.getExtras());
                }
            } catch (PackageManager.NameNotFoundException e) {
                LogUtil.error(getClass(), e.getMessage());
            }
        }
    };

    public void onDestroy() {
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (getSelfPresenter() != null) {
            int size = getSelfPresenter().size();
            for (int i = 0; i < size; i++) {
                getSelfPresenter().get(i).detachView();
            }
            getSelfPresenter().clear();
        }

        if (broadcastReceiver != null) {
            try {
                LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(broadcastReceiver);
            } catch (Exception e) {
                LogUtil.error(getClass(), e.getMessage());
            } finally {
                broadcastReceiver = null;
            }
        }
    }

    public void onResume() {
        if (getPersenter() != null) {
            getPersenter().onResume();
        }
        if (getSelfPresenter() != null) {
            int size = getSelfPresenter().size();
            for (int i = 0; i < size; i++) {
                getSelfPresenter().get(i).onResume();
            }
        }
    }

    public void onPause() {
        if (getPersenter() != null) {
            getPersenter().onPause();
        }
        if (getSelfPresenter() != null) {
            int size = getSelfPresenter().size();
            for (int i = 0; i < size; i++) {
                getSelfPresenter().get(i).onPause();
            }
        }
    }

    public void setUserVisibleHint(boolean isVisibleToUser) {

    }

    public void setProessDelegate(OnProessViewDelegate delegate) {
        this.mDelegate = delegate;
    }

    public List<IBasePresenter> createSelfPresenter() {
        return null;
    }

    protected final List<IBasePresenter> getSelfPresenter() {
        if (CollectionUtil.isEmpty(mSelfPresenter)) {
            mSelfPresenter = createSelfPresenter();
        }
        return mSelfPresenter;
    }


    /**
     * 创建prensenter
     */
    public T createPresenter() {
        Class clazz = ClassUtil.getGenericClass(getClass());
        if (clazz != null) {
            try {
                return (T) clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    @Override
    public Context getViewContext() {
        return getContext();
    }

    @Override
    public void showToast(String msg) {
        ToastUtil.show(getContext(), msg);
    }

    @Override
    public void showToast(int msg) {
        ToastUtil.show(getContext(), msg);
    }

    @Override
    public void loadError(int errorCode, String message) {

    }

    @Override
    public void hasMore(boolean hasMore) {

    }

    /**
     * 接收其他类型的广播
     *
     * @param intent 上下文对象
     * @param bundle 数据集
     */
    protected void onReceiveBroadcast(int intent, Bundle bundle) {

    }

    protected abstract View onCreateView();

    protected abstract void findViews();

    protected abstract void initialize();

    @Override
    public void loadComplete(List<K> dataSource) {

    }

    @Override
    public void loadComplete(K dataSource) {

    }

    public T getPersenter() {
        if (mPresenter == null) {
            mPresenter = createPresenter();
        }
        return mPresenter;
    }
}
